package com.hdsx.netty.tomcatserver;

import io.netty.util.CharsetUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author 占贤银
 * time 2024/8/4 11:33
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class NioServerDemo1 {

    static Selector selector;

    static {
        try {
            selector = Selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用NioServer搭建一个服务
     * 把channel注册到选择器上 由Selector来监听感兴趣的事件，并做出相应的处理
     * @param args
     */
    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            // 绑定一个端口号
            serverSocketChannel.bind(new InetSocketAddress(8080));
            // 设置成非阻塞
            serverSocketChannel.configureBlocking(false);
            // 把chnnel注册到Selector
            // 注册一个等待客户端连接的事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    process(key);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void process(SelectionKey key) throws IOException {
        if (key.isAcceptable()) { // 连接事件
            // todo 等待客户端的连接
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
            // serverSocketChannel.accept();
            SocketChannel socketChannel = serverSocketChannel.accept(); // 阻塞 等待连接
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
        } else if (key.isReadable()) {
            // todo 读数据
            SocketChannel channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int len = channel.read(buffer);
            if (len != -1) {
                buffer.flip();
                String content = new String(buffer.array(), 0, len);
                SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_WRITE);
                selectionKey.attach(content); // 把数据携带到下一个监听事件上
            }
        } else if (key.isWritable()) {
            SocketChannel channel = (SocketChannel) key.channel();
            String content = (String) key.attachment();
            ByteBuffer block = ByteBuffer.wrap(("输出内容是：" + content).getBytes(CharsetUtil.UTF_8));
            if (block != null) {
                channel.write(block);
            } else {
                channel.close();
            }
        }
    }
}
